package com.dongnam.quanly.web.security;

import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dongnam.quanly.common.model.UserRight.AccessLevel;
import com.dongnam.quanly.web.UserBean;

public class AccessControlPhaseListener implements PhaseListener {

	private static final long serialVersionUID = 1L;

	static final Logger logger = LoggerFactory.getLogger(AccessControlPhaseListener.class);

	private UrlFilter restrictedArea;

	// private String previousViewID = "";
	// private boolean isBackToLogin = true;

	public AccessControlPhaseListener() {
		restrictedArea = new UrlFilter();
		restrictedArea.include("*").exclude("/pages/error/*").exclude("/login.xhtml").exclude("/loginFailure.xhtml");

	}

	@Override
	public void afterPhase(PhaseEvent event) {
		FacesContext facesContext = event.getFacesContext();
		UserBean session = facesContext.getApplication().evaluateExpressionGet(facesContext, "#{UserBean}",
				UserBean.class);
		if (session == null) {
			logger.info("unable to retrieve Session!");
			return;
		}

		String viewId = facesContext.getViewRoot().getViewId();
		logger.debug("viewId = {}", viewId);

		if (restrictedArea.matches(viewId)) {

			if (!session.isLoggedIn()) {
				session.setPreviousViewID(viewId);
				facesContext.getApplication().getNavigationHandler()
						.handleNavigation(facesContext, null, "/login.xhtml?faces-redirect=true");

				session.setBackToLogin(true);
			} else {
				if (session.isBackToLogin()) {
					if (session.getPreviousViewID() != null && session.getPreviousViewID().length() != 0) {
						facesContext
								.getApplication()
								.getNavigationHandler()
								.handleNavigation(facesContext, null,
										session.getPreviousViewID() + "?faces-redirect=true");
					}

					session.setBackToLogin(false);
				}
			}
		}
	}

	@Override
	public void beforePhase(PhaseEvent event) {
		// back button forces refresh instead of reusing cache
		FacesContext facesContext = event.getFacesContext();
		HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
		response.addHeader("Pragma", "no-cache");
		response.addHeader("Cache-Control", "no-cache");
		response.addHeader("Cache-Control", "no-store");
		response.addHeader("Cache-Control", "must-revalidate");
		response.addHeader("Expires", "0");
	}

	@Override
	public PhaseId getPhaseId() {
		return PhaseId.RESTORE_VIEW;
	}
}
